package com.icss.train_sys_back.controller.home;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.icss.train_sys_back.entity.ResponseResult;
import com.icss.train_sys_back.entity.ResultEnum;
import com.icss.train_sys_back.entity.home.OrderEntity;
import com.icss.train_sys_back.entity.home.PassengerEntity;
import com.icss.train_sys_back.entity.home.PassengerUserEntity;
import com.icss.train_sys_back.entity.system_manage.UserEntity;
import com.icss.train_sys_back.mapper.system_manage.UserMapper;
import com.icss.train_sys_back.service.system_service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.json.JSONObject;

import com.icss.train_sys_back.utils.FaceUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author wk
 * @desc
 * @date 2025/9/15 17:52
 */
@RestController
@RequestMapping("/home")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    //用户登录
    @PostMapping("/login")
    public @ResponseBody ResponseResult login(@RequestBody UserEntity user) {
        log.info("登录，user = {}", user);
        UserEntity isUser = userService.login(user);
        log.info("isUser :{}", isUser);
        if (isUser != null) {
            //用户信息存储到saToken中
            StpUtil.login(isUser.getUserId());
            //返回token信息给前端
            String token = StpUtil.getTokenValue();
            Map<String, Object> res = new HashMap<>();
            res.put("token", token);
            res.put("user", isUser);
            return ResponseResult.success(res);
        } else {
            return ResponseResult.fail(ResultEnum.LOGIN_NAME_PWD_ERROR);
        }

    }

    //检查用户名是否存在
    @GetMapping("/checkUserName")
    public ResponseResult checkUserName(@RequestParam String username) {
        log.info("检查用户名是否存在 username = {}", username);
        boolean res = userService.checkUserName(username);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //检查手机号是否存在
    @GetMapping("/checkPhone")
    public ResponseResult checkPhone(@RequestParam String phone) {
        log.info("检查手机号是否存在 phone = {}", phone);
        boolean res = userService.checkPhone(phone);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //检查邮箱号是否存在
    @GetMapping("/checkEmail")
    public ResponseResult checkEmail(@RequestParam String email) {
        log.info("检查email是否存在 email = {}", email);
        boolean res = userService.checkEmail(email);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //用户注册
    @PostMapping("/register")
    public ResponseResult register(@RequestBody UserEntity user) {
        log.info("用户注册 user = {}", user);
        userService.register(user);
        UserEntity userEntity = userMapper.checkUserName(user.getUsername());
        Integer userId = userEntity.getUserId();
        user.setUserId(userId);
        return userId != null ? ResponseResult.success(user) : ResponseResult.fail(ResultEnum.FAIL);
    }

    // 人脸识别注册
    @PostMapping("/faceRegister")
    @ResponseBody
    public ResponseResult faceRegister(@RequestBody Map<String, String> faceData) {
        log.info("人脸识别注册请求: {}", faceData.get("userInfo"));
        try {
            // 1. 参数校验优化
            if (faceData == null) {
                log.warn("人脸注册请求数据为空");
                return ResponseResult.fail(ResultEnum.PARAM_ERROR);
            }

            String image = faceData.get("image");
            String userInfo = faceData.get("userInfo");
            String userIdStr = faceData.get("userId");
            String groupId = faceData.get("groupId");

            // 用户ID校验
            if (userIdStr == null || userIdStr.isEmpty() || !userIdStr.matches("\\d+")) {
                log.warn("用户ID格式错误: {}", userIdStr);
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            // 图片校验增强
            if (image == null || image.isEmpty()) {
                log.warn("人脸照片为空");
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            // 组ID默认值设置
            if (groupId == null || groupId.isEmpty()) {
                groupId = "login_face_1";
                log.info("组ID为空，使用默认值: {}", groupId);
            }

            Integer userId;
            try {
                userId = Integer.valueOf(userIdStr);
            } catch (NumberFormatException e) {
                log.error("用户ID转换失败: {}", userIdStr);
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            // 2. 调用FaceUtils进行人脸注册，增加重试逻辑
            String registerResult = null;
            int maxRetries = 2;
            int retryCount = 0;
            boolean success = false;

            while (retryCount <= maxRetries && !success) {
                try {
                    registerResult = FaceUtils.faceRegister(image, userInfo, userIdStr, groupId);
                    success = true;
                } catch (Exception e) {
                    retryCount++;
                    log.warn("人脸注册失败，正在重试 ({}): {}", retryCount, e.getMessage());
                    if (retryCount > maxRetries) {
                        log.error("人脸注册超过最大重试次数", e);
                        return ResponseResult.fail(ResultEnum.FAIL);
                    }
                    // 等待100ms后重试
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                }
            }

            log.info("FaceUtils返回结果: {}", registerResult);

            // 3. 解析百度AI返回的结果，增强错误处理
            JSONObject jsonResult = new JSONObject(registerResult);
            int errorCode = jsonResult.optInt("error_code", -1); // 默认值-1表示获取失败

            if (errorCode != 0) { // 只有当error_code不等于0时才认为失败
                String errorMsg = jsonResult.optString("error_msg", "未知错误");
                log.warn("人脸注册失败，错误码: {}, 错误信息: {}", errorCode, errorMsg);

                // 针对常见错误提供更友好的提示
                String friendlyMsg = getFriendlyErrorMessage(errorCode, errorMsg);
                return ResponseResult.fail(ResultEnum.FAIL);
            } else {
                // 更新人脸注册状态
                try {
                    userService.updateFaceRegisterStatus(userId);
                    log.info("人脸注册成功，用户ID: {}", userId);
                    Map<String, Object> data = new HashMap<>();
                    data.put("faceResult", jsonResult);
                    return ResponseResult.success(data);
                } catch (Exception e) {
                    log.error("更新人脸注册状态失败: {}", e.getMessage());
                    // 这里不影响人脸注册本身的成功状态，只记录错误
                    Map<String, Object> data = new HashMap<>();
                    data.put("faceResult", jsonResult);
                    data.put("statusUpdateFailed", true);
                    return ResponseResult.success(data);
                }
            }
        } catch (Exception e) {
            log.error("人脸注册异常", e);
            return ResponseResult.fail(ResultEnum.FAIL);
        }
    }

    // 辅助方法：根据百度AI错误码提供友好提示
    private String getFriendlyErrorMessage(int errorCode, String errorMsg) {
        switch (errorCode) {
            case 222202:
                return "未检测到人脸，请确保照片清晰包含人脸";
            case 222203:
                return "照片中人脸质量不佳，请更换清晰照片";
            case 222207:
                return "人脸注册失败，该人脸已存在";
            case 17:
                return "请求过于频繁，请稍后再试";
            default:
                return "人脸注册失败: " + errorMsg;
        }
    }

    // 人脸登录
    @PostMapping("/faceLogin")
    public ResponseResult faceLogin(@RequestBody Map<String, String> userInfo) {
        log.info("用户人脸识别登录 userInfo = {}", userInfo.get("username"));
        String username = userInfo.get("username");
        String image = userInfo.get("image");

        // 根据username获取该用户信息
        UserEntity user = userMapper.checkUserName(username);
        if (user == null) {
            log.error("用户不存在: {}", username);
            return ResponseResult.fail(ResultEnum.FAIL);
        }

        if (user.getFaceRegister() == 0 || user.getFaceRegister() == null) {
            // 未进行人脸注册
            log.error("用户未进行人脸注册: {}", username);
            return ResponseResult.fail(ResultEnum.NOT_FACE_REGISTER);
        }

        Integer userId = user.getUserId();

        // 人脸识别登录，groupIdList应该是包含用户所在组的列表，而不是单个用户ID
        String resp = FaceUtils.faceLogin(image, "login_face_1"); // 假设用户组ID为login_face_1
        log.info("人脸识别登录结果 resp = {} ", resp);

        // 解析结果，判断是否登录成功
        JSONObject jsonObject = new JSONObject(resp);

        // 获取百度AI返回的错误码和结果
        Integer errorCode = jsonObject.optInt("error_code");
        String errorMsg = jsonObject.optString("error_msg");

        if (errorCode == 0) {
            // 登录成功，获取匹配结果
            JSONObject result = jsonObject.optJSONObject("result");
            if (result != null) {
                // 获取分数最高的匹配结果
                JSONObject userList = result.optJSONArray("user_list").optJSONObject(0);
                if (userList != null) {
                    String userIdStr = userList.optString("user_id");
                    Double score = userList.optDouble("score");
                    log.info("人脸匹配成功: userId={}, 相似度分数={}", userIdStr, score);

                    // 用户信息存储到saToken中
                    StpUtil.login(user);
                    // 返回token信息给前端
                    String token = StpUtil.getTokenValue();
                    Map<String, Object> res = new HashMap<>();
                    res.put("token", token);
                    res.put("user", user);
                    return ResponseResult.success(res);
                }
            }
        } else {
            // 登录失败
            log.error("人脸识别登录失败: 错误码={}, 错误信息={}", errorCode, errorMsg);
            // 可以添加错误码映射，返回友好提示
            return ResponseResult.fail(ResultEnum.FAIL);
        }
        // 其他情况返回失败
        return ResponseResult.fail(ResultEnum.FAIL);
    }

    //根据用户Id查询乘车人列表
    @GetMapping("/passenger/listByUserId")
    public ResponseResult getPassengerListByUserId(@RequestParam("userId") Integer userId) {
        log.info("根据用户Id查询乘车人列表  userId = {}", userId);
        List<PassengerEntity> passengerEntityList = userService.getPassengerListByUserId(userId);
        return ResponseResult.success(passengerEntityList);
    }

    //添加乘车人
    @PostMapping("/passenger/add")
    public ResponseResult addPassenger(@RequestBody PassengerEntity passenger) {
        log.info("添加乘车人 passenger = {}", passenger);

        //根据电话号码查询用户表中的用户信息，方便往乘车人和用户的映射表中插入数据
        UserEntity user = userMapper.findUser(passenger.getPhone());
        if (user == null) {
            return ResponseResult.fail(ResultEnum.FIND_USER_ERROR);
        }
        Integer flag = userMapper.addPassenger(passenger);
        if (flag == 1) {
            flag = userMapper.addPassengerUser(passenger.getPassengerId(), user.getUserId());
        } else {
            flag = 0;
        }
        return flag == 1 ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //更新乘车人
    @PutMapping("/passenger/update/{passengerId}")
    public ResponseResult updatedPassenger(@PathVariable("passengerId") Integer passengerId,
                                           @RequestBody PassengerEntity passenger) {
        log.info("更新乘车人 passenger = {}, passengerId = {}", passenger, passengerId);
        passenger.setPassengerId(passengerId);
        Integer flag = userMapper.updatePassenger(passenger);
        return flag == 1 ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //删除乘车人
    @DeleteMapping("/passenger/delete/{passengerId}")
    public ResponseResult deletePassenger(@PathVariable("passengerId") Integer passengerId) {
        log.info("删除乘车人  passengerId = {}", passengerId);
        Integer flag = userMapper.deletePassenger(passengerId);
        return flag == 1 ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //根据用户Id查询用户信息
    @GetMapping("/getUserInfo")
    public ResponseResult getUserInfo(@RequestParam Integer userId) {
        log.info("根据用户Id查询用户信息 userId = {}", userId);
        UserEntity user = userMapper.getUserInfoByUserId(userId);
        return user != null ? ResponseResult.success(user) : ResponseResult.fail(ResultEnum.FAIL);
    }

    //更新用户信息
    @PostMapping("/updateUserInfo")
    public ResponseResult updateUserInfo(@RequestBody UserEntity user) {
        log.info("更新用户信息  user = {}", user);
        boolean flag = userMapper.updateUserEmailAndPhoneAndUserNameByUserId(user);
        return flag ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //退出系统
    @PostMapping("/logout/{userId}")
    public ResponseResult logout(@PathVariable("userId") Integer userId) {
        log.info("退出登录 userId ={}", userId);
        StpUtil.logout(userId);
        String tokenValue = StpUtil.getTokenValue();
        return tokenValue == null ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //根据手机号查询用户信息
    @GetMapping("/passenger/checkUser")
    public ResponseResult getUserInfoByPhone(@RequestParam String phone) {
        log.info("根据手机号查询用户信息 phone = {}", phone);
        UserEntity user = userMapper.getUserInfoByPhone(phone);
        return user != null ? ResponseResult.success(user) : ResponseResult.fail(ResultEnum.FAIL);
    }

    //人脸信息更改时验证密码
    @PostMapping("/verifyPassword")
    public ResponseResult verifyPassword(@RequestParam Integer userId,
                                         @RequestParam String password) {
        log.info("人脸信息更改时验证密码 userId = {} , pwd = {}", userId, password);
        return userService.verifyPwd(userId, password);
    }

    //历史订单查询
    @GetMapping("/getHistoryOrderList")
    public ResponseResult getHistoryOrderList(@RequestParam(defaultValue = "1") Integer page, //页码
                                              @RequestParam(defaultValue = "10") Integer pageSize, //尺寸
                                              @RequestParam Integer userId,//登陆人Id
                                              @RequestParam(required = false) LocalDate startTime,//范围查询
                                              @RequestParam(required = false) LocalDate endTime,
                                              @RequestParam(required = false) String orderId //订单Id
    ) {
        log.info("历史订单查询  page = {},pageSize = {},userId = {},startTime = {},endTime = {},orderId = {}",
                page, pageSize, userId, startTime, endTime, orderId);
        PageHelper.startPage(page,pageSize);
        List<OrderEntity> orderEntityList = userService.getHistoryOrderList(userId,startTime,endTime,orderId);
        PageInfo<OrderEntity> pageInfo = new PageInfo<>(orderEntityList);

        return ResponseResult.success(pageInfo);
    }
}

